//
//  XS_BundlePath.swift
//  Alamofire
//
//  Created by 韩云智 on 2020/7/14.
//
//  获取本地Bundle路径及文件

import AVFoundation
import SDWebImage

public func xs_getBundle(_ isFramework: Bool = true, fName: String, bName: String? = nil) -> Bundle {
    guard isFramework,
        var bundleUrl = Bundle.main.url(forResource: "Frameworks", withExtension: nil) else { return Bundle.main }
    bundleUrl = bundleUrl.appendingPathComponent(fName)
    bundleUrl = bundleUrl.appendingPathExtension("framework")
    let bundle = Bundle(url: bundleUrl)
    guard let url = bundle?.url(forResource: bName, withExtension: "bundle") else {
        return bundle ?? Bundle.main
    }
    return Bundle(url: url) ?? Bundle.main
}
public func xs_getBundleImg(_ imgName: String, type: String? = "png", bundle: Bundle) -> UIImage? {
    var filePath: String? = nil
    switch type {
    case "png":
        var arr: [Int] = [3, 2, 1]
        let scale = Int(ceil(UIScreen.main.scale))
        if let index = arr.firstIndex(where: { $0 == scale }), index != 0 {
            arr.swapAt(index, 0)
        }
        for item in arr {
            if let path = bundle.path(forResource: imgName + "@\(item)x", ofType: type),
                FileManager.default.fileExists(atPath: path){
                filePath = path
                break
            }
        }
    default:
        filePath = bundle.path(forResource: imgName, ofType: type)
    }
    guard let file = filePath else { return nil }
    return UIImage(contentsOfFile: file)
}
 
public func xs_getBundlePath(_ name: String, ofType: String, bundle: Bundle? = nil) -> String? {
    return (bundle ?? Bundle.main).path(forResource: name, ofType: ofType)
}

public func xs_getGifPath(_ name: String, bundle: Bundle? = nil) -> String? {
    return xs_getBundlePath(name, ofType: "gif", bundle: bundle)
}
public func xs_getGifData(_ name: String, bundle: Bundle? = nil) -> Data? {
    guard let path = xs_getGifPath(name, bundle: bundle) else { return nil}
    return try? Data(contentsOf: URL(fileURLWithPath: path))
}
public func xs_getGif(_ name: String, bundle: Bundle? = nil) -> UIImage? {
    guard let data = xs_getGifData(name, bundle: bundle) else { return nil}
    return UIImage.sd_animatedGIF(with: data)
}

public func xs_getSoundPath(_ name: String, type: String = "mp3", bundle: Bundle? = nil) -> String? {
    return xs_getBundlePath(name, ofType: type, bundle: bundle)
}
public func xs_getSoundUrl(_ name: String, type: String = "mp3", bundle: Bundle? = nil) -> URL? {
    guard let path = xs_getSoundPath(name, type: type, bundle: bundle) else { return nil}
    return URL(fileURLWithPath: path)
}
public func xs_getSound(_ name: String, type: String = "mp3", bundle: Bundle? = nil) -> AVPlayer? {
    guard let url = xs_getSoundUrl(name, type: type, bundle: bundle) else { return nil}
    let item = AVPlayerItem(url: url)
    return AVPlayer(playerItem: item)
}
